package org.toy.wechat.gym.service.impl;

import com.mzlion.core.lang.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.toy.wechat.core.common.exception.BusinessException;
import org.toy.wechat.gym.cache.UserCache;
import org.toy.wechat.gym.dao.GymUserInfoMapper;
import org.toy.wechat.gym.domain.GymUserInfo;
import org.toy.wechat.gym.request.GymLoginRequest;
import org.toy.wechat.gym.response.GymLoginResponse;
import org.toy.wechat.gym.rpc.WxRpc;
import org.toy.wechat.gym.rpc.model.WxSession;
import org.toy.wechat.gym.service.IGymLoginService;

/**
 * @Description 登录服务
 * @Author devin
 * @Date: 2020/2/22 0022 22:14
 */
@Service
@Slf4j
public class GymLoginServiceImpl implements IGymLoginService {

    @Autowired
    private GymUserInfoMapper gymUserInfoMapper;

    @Autowired
    private WxRpc wxRpc;

    @Autowired
    private UserCache userCache;


    @Override
    public GymLoginResponse login(GymLoginRequest gymLoginRequest) {
        WxSession wxSession = wxRpc.codeToSession(gymLoginRequest.getWxCode());
        if (null == wxSession || StringUtils.isEmpty(wxSession.getOpenId())) {
            throw new BusinessException("微信服务请求报错！");
        }
        String openId = wxSession.getOpenId();
        String queryOpenId = userCache.get(openId, String.class);
        if (!StringUtils.isEmpty(queryOpenId)) {
            return GymLoginResponse.builder().signature(queryOpenId).build();
        }
        GymUserInfo gymUserInfo = new GymUserInfo();
        gymUserInfo.setOpenId(openId);
        gymUserInfo.setUnionId(wxSession.getUnionId());
        gymUserInfoMapper.insertSelective(gymUserInfo);
        return GymLoginResponse.builder().signature(openId).build();
    }
}
